package com.sinog.biz.service.business.impl;

import com.sinog.biz.service.business.EncryptionService;
import com.sinog.biz.util.MainUtil;
import com.sinog.core.util.AesUtil;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;

/**
 * @desc 数据加密
 * @author ybl
 * @date 2022/10/18
 */
@Slf4j
@Service
public class EncryptionServiceImpl implements EncryptionService {

    private static final byte[] DECRYPTED = new byte[0];

    @Override
    public Result encryptionData(String data) {
        Map<String,Object> map = JsonUtil.toMap(data);
        //1.账号；2.数据库；3.身份证 21.数据库解密 31 身份证解密
        switch((int)map.get("type")){
            case 1:
                return Result.success(encryptedCode((String)map.get("content")));
            case 2:
                return Result.success(MainUtil.main3((String)map.get("content")));
            case 3:
                return Result.success(MainUtil.main2((String)map.get("content")));
            case 21:
                return Result.success(MainUtil.main31((String)map.get("content")));
            case 31:
                return Result.success(MainUtil.main21((String)map.get("content")));
            default:
                break;
        }
        return Result.failure("");
    }

    /**
     * 用户密码加密
     * @param pwd 前台过来的密码
     * @return String
     */
    private String encryptedCode(String pwd){
        //前端传递密码解密
        String key = "abcdefghijklmn12";
        String iv = "abcdefghijklmn12";
        //解密
        byte[] decrypted = DECRYPTED;
        try {
            decrypted = AesUtil.aesCbcDecrypt(AesUtil.decryptBase64(pwd),key.getBytes(),iv.getBytes());
        } catch(Exception e) {
            log.error("发生异常:",e);
        }
        pwd = AesUtil.byteToString(decrypted);
        BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
        pwd = bpe.encode(pwd);
        return pwd;
    }



}